package com.my.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.entity.Subject;
import com.my.service.SubjectService;
import com.my.util.Rest;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
public class SubjectController {

    @Resource
    private SubjectService service;

    @GetMapping("subject/get")
    public Rest get() {
        return Rest.ok().setData("tree", TreeUtil.build(service.getList(), 0L, (s, t) -> {
            t.setId(s.getId());
            t.setParentId(s.getParentId());
            t.setName(s.getName());
            t.putExtra("parentName", s.getDeep() == 0 ? "目录" : s.getParentName());
            t.putExtra("deep", s.getDeep());
            t.putExtra("sort", s.getSort());
            t.putExtra("createTime", DateUtil.format(s.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        }));
    }

    @GetMapping("subject/tree")
    public Rest tree() {
        List<Subject> list = new ArrayList<>();
        list.add(new Subject().setId(0L).setParentId(-1L).setName("目录").setDeep(-1));
        list.addAll(service.getList());
        return Rest.ok().setData("tree", TreeUtil.build(list, -1L, (s, t) -> {
            t.setId(s.getId());
            t.setParentId(s.getParentId());
            t.setName(s.getName());
            t.putExtra("parentName", s.getParentName() == null ? "" : s.getParentName());
            t.putExtra("title", s.getName());
            t.putExtra("deep", s.getDeep());
        }));
    }

    @PostMapping("subjects")
    public Rest add(@RequestBody Subject subject) {
        if(service.save(subject)) {
            return Rest.ok("添加成功！");
        }
        return Rest.err("添加失败");
    }

    @PutMapping("subjects")
    public Rest edit(@RequestBody Subject subject) {
        if(service.updateById(subject)) {
            return Rest.ok("修改成功！");
        }
        return Rest.err("修改失败");
    }

    @DeleteMapping("subjects")
    public Rest del(Long id) {
        if(!service.list(new QueryWrapper<Subject>().eq("parent_id", id)).isEmpty()) {
            return Rest.err("无法删除，此节点下还有子节点！");
        }
        if(service.removeById(id)) {
            return Rest.ok("删除成功！");
        }
        return Rest.err("删除失败！");
    }

}
